package org.elephantt.webby;

import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.handler.AbstractHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jetty handler that delegates to the Webby dispatcher. Acts as an adapter between Jetty and Webby.
 */
public class WebbyDispatchHandler extends AbstractHandler {
  private final Dispatcher dispatcher;

  public WebbyDispatchHandler(Dispatcher dispatcher) {
    this.dispatcher = dispatcher;
  }

  public void handle(String s, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {
    org.mortbay.jetty.Request baseRequest = (request instanceof org.mortbay.jetty.Request) ? (org.mortbay.jetty.Request) request : HttpConnection.getCurrentConnection().getRequest();
    dispatcher.dispatch(request, response);
    baseRequest.setHandled(true);
  }
}